

package com.kimo.shop.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kimo.shop.bean.enums.OrderInvoiceState;
import com.kimo.shop.bean.model.OrderInvoice;
import com.kimo.shop.common.exception.KimoShopBindException;
import com.kimo.shop.common.util.PageParam;
import com.kimo.shop.security.admin.util.SecurityUtils;
import com.kimo.shop.service.OrderInvoiceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.Objects;


/**
 *
 *
 * @author kimo-taozhouchuan
 * @date 2021-08-16 14:22:47
 */
@RestController("multishopOrderInvoiceController")
@AllArgsConstructor
@RequestMapping("/m/orderInvoice" )
@Api(tags = "商家端订单发票")
public class OrderInvoiceController {

    private final OrderInvoiceService orderInvoiceService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param orderInvoice
     * @return 分页数据
     */
    @ApiOperation(value = "分页查询")
    @GetMapping("/page" )
    public ResponseEntity<IPage<OrderInvoice>> getOrderInvoicePage(PageParam<OrderInvoice> page, OrderInvoice orderInvoice) {
        orderInvoice.setShopId(SecurityUtils.getSysUser().getShopId());
        return ResponseEntity.ok(orderInvoiceService.page(page,orderInvoice));
    }


    /**
     * 通过id查询
     * @param orderInvoiceId id
     * @return 单个数据
     */
    @ApiOperation(value = "通过id查询")
    @GetMapping("/info/{orderInvoiceId}" )
    @PreAuthorize("@pms.hasPermission('order:orderInvoice:update')")
    public ResponseEntity<OrderInvoice> getById(@PathVariable("orderInvoiceId") Long orderInvoiceId) {
        return ResponseEntity.ok(orderInvoiceService.getById(orderInvoiceId));
    }

    /**
     * 修改
     * @param orderInvoice
     * @return 是否修改成功
     */
    @ApiOperation(value = "开票，上传文件")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('order:orderInvoice:commit')")
    public ResponseEntity<Boolean> updateById(@RequestBody @Valid OrderInvoice orderInvoice) {
        if (Objects.isNull(orderInvoice.getFileId())){
            //商家提交，不上传文件不给保存
            throw new KimoShopBindException("kimo.file.isNot.exist");
        }
        orderInvoice.setInvoiceState(OrderInvoiceState.ISSUED.value());
        orderInvoice.setUploadTime(new Date());
        return ResponseEntity.ok(orderInvoiceService.updateById(orderInvoice));
    }

    @ApiOperation(value = "该订单是否已经上传发票")
    @GetMapping("/is_upload")
    public ResponseEntity<Boolean> isUpload(@RequestParam String orderNumber) {
        return ResponseEntity.ok(orderInvoiceService.isUpload(orderNumber));
    }

}
